package com.tianji.promotion.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.tianji.common.constants.CacheConstant.LOCK_PREFIX;

@Component
public class RedisLock {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean tryLock(String lockName, long expire, TimeUnit timeUnit) {
        return redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX+lockName, Thread.currentThread().getName(), expire, timeUnit);
    }

    public void unlock(String lockName) {
         redisTemplate.delete(LOCK_PREFIX+lockName);
    }
}
